package com.ruoyi.zhmk.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.*;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.faceApi.click.FaceApiClick;
import com.ruoyi.zhmk.domain.ZhmkDoorDevice;
import com.ruoyi.zhmk.domain.request.SendPersonRequest;
import com.ruoyi.zhmk.domain.response.SendPersonResponse;
import com.ruoyi.zhmk.mapper.ZhmkDoorDeviceMapper;
import com.ruoyi.zhmk.utils.FaceApiUtil;
import com.ruoyi.zhmk.utils.ImageIOUtils;
import com.ylsoft.android.iacterminal.net.thrift.server.transaction.TWhiteListPerson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.zhmk.mapper.ZhmkPersonMapper;
import com.ruoyi.zhmk.domain.ZhmkPerson;
import com.ruoyi.zhmk.service.IZhmkPersonService;

/**
 * 人员信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-06-24
 */
@Service
public class ZhmkPersonServiceImpl implements IZhmkPersonService 
{
    @Autowired
    private ZhmkPersonMapper zhmkPersonMapper;
    @Autowired
    private ZhmkDoorDeviceMapper zhmkDoorDeviceMapper;

    /**
     * 查询人员信息
     * 
     * @param id 人员信息ID
     * @return 人员信息
     */
    @Override
    public ZhmkPerson selectZhmkPersonById(Long id)
    {
        return zhmkPersonMapper.selectZhmkPersonById(id);
    }

    /**
     * 查询人员信息列表
     * 
     * @param zhmkPerson 人员信息
     * @return 人员信息
     */
    @Override
    public List<ZhmkPerson> selectZhmkPersonList(ZhmkPerson zhmkPerson)
    {
        return zhmkPersonMapper.selectZhmkPersonList(zhmkPerson);
    }

    /**
     * 新增人员信息
     * 
     * @param zhmkPerson 人员信息
     * @return 结果
     */
    @Override
    public int insertZhmkPerson(ZhmkPerson zhmkPerson)
    {
        zhmkPerson.setCreateTime(DateUtils.getNowDate());
        zhmkPerson.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
        return zhmkPersonMapper.insertZhmkPerson(zhmkPerson);
    }

    /**
     * 修改人员信息
     * 
     * @param zhmkPerson 人员信息
     * @return 结果
     */
    @Override
    public int updateZhmkPerson(ZhmkPerson zhmkPerson)
    {
        //查询出要修改人员
        ZhmkPerson zhmkPerson1 = zhmkPersonMapper.selectZhmkPersonById(zhmkPerson.getId());
        //查询出该人员最近的一条请假未归记录

        zhmkPerson.setUpdateTime(DateUtils.getNowDate());
        return zhmkPersonMapper.updateZhmkPerson(zhmkPerson);
    }

    /**
     * 批量删除人员信息
     * 
     * @param ids 需要删除的人员信息ID
     * @return 结果
     */
    @Override
    public int deleteZhmkPersonByIds(Long[] ids)
    {
        List<ZhmkDoorDevice> zhmkDoorDevices = zhmkDoorDeviceMapper.selectZhmkDoorDeviceList(new ZhmkDoorDevice());
        List<ZhmkPerson> zhmkPeople = zhmkPersonMapper.selectZhmkPersonListByIds(ids);
        for (ZhmkDoorDevice zhmkDoorDevice : zhmkDoorDevices) {
            for (ZhmkPerson zhmkPerson : zhmkPeople) {
                FaceApiClick faceApiClick = FaceApiUtil.getFaceApiClick();
                faceApiClick.deleteWhiteListPerson(zhmkDoorDevice.getIp(),String.valueOf(zhmkPerson.getId()));
            }
        }

        return zhmkPersonMapper.deleteZhmkPersonByIds(ids);
    }

    /**
     * 删除人员信息信息
     * 
     * @param id 人员信息ID
     * @return 结果
     */
    @Override
    public int deleteZhmkPersonById(Long id)
    {
        List<ZhmkDoorDevice> zhmkDoorDevices = zhmkDoorDeviceMapper.selectZhmkDoorDeviceList(new ZhmkDoorDevice());
        ZhmkPerson zhmkPerson1 = zhmkPersonMapper.selectZhmkPersonById(id);
        for (ZhmkDoorDevice zhmkDoorDevice : zhmkDoorDevices) {
            FaceApiClick faceApiClick = FaceApiUtil.getFaceApiClick();
            faceApiClick.deleteWhiteListPerson(zhmkDoorDevice.getIp(),String.valueOf(zhmkPerson1.getId()));
        }
        return zhmkPersonMapper.deleteZhmkPersonById(id);
    }

    /**
     * 人员下发
     * @param sendPersonRequest
     * @return
     */
    @Override
    public AjaxResult personSend(SendPersonRequest sendPersonRequest) {
        Map<Long,Integer> personMap = new HashMap<>();
        if(sendPersonRequest.getDeviceIdList() == null || sendPersonRequest.getDeviceIdList().size()<=0){
            throw new CustomException("参数错误", HttpStatus.BAD_REQUEST);
        }
        List<Long> deviceIdList = sendPersonRequest.getDeviceIdList();
        List<SendPersonResponse> sendPersonResponseList = new ArrayList<>();
        for (Long aLong : deviceIdList) {
            //根据设备id查询出设备信息
            ZhmkDoorDevice zhmkDoorDevice = zhmkDoorDeviceMapper.selectZhmkDoorDeviceById(aLong);
            if(zhmkDoorDevice == null){
                throw new CustomException("查询不到设备", HttpStatus.ERROR);
            }
            //获取人员信息
            List<Long> personIdList = sendPersonRequest.getPersonIdList();
            if(personIdList.size()<=0){
                throw new CustomException("人员为空", HttpStatus.BAD_REQUEST);
            }
            Long[] ids = new Long[personIdList.size()];
            List<ZhmkPerson> zhmkPeopleList = zhmkPersonMapper.selectZhmkPersonListByIds(personIdList.toArray(ids));
            /**
             * 下发成功数量
             */
            int sendSuccessCount = 0;
            /**
             * 下发失败数量
             */
            int sendFailCount = 0;
            for (ZhmkPerson zhmkPerson : zhmkPeopleList) {
                //读取图片数据
                String avatar = zhmkPerson.getAvatar();
                //处理图片路径，获取文件位置
                String uploadPath = RuoYiConfig.getUploadPath();
                String replace = avatar.replace("/profile/upload", "");
                String filePath = uploadPath+replace;
                byte[] imageDataByte = null;
                try {
                    File file = new File(filePath);
                    imageDataByte = Files.readAllBytes(file.toPath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(imageDataByte == null){
                    //下发失败
                    sendFailCount ++;
                    break;
                }
                //ByteBuffer buf = ByteBuffer.wrap(imageDataByte);
                TWhiteListPerson tPerson = new TWhiteListPerson();
                tPerson.setImageData(imageDataByte);
                tPerson.setStartTime(System.currentTimeMillis());
                Calendar cal = Calendar.getInstance();
                cal.setTime(new Date());
                cal.add(Calendar.YEAR, 100);
                tPerson.setEndTime(cal.getTime().getTime());
                //tPerson.setImageData(buf);
                tPerson.setName(zhmkPerson.getUserName());
                tPerson.setImageType(1);
                tPerson.setPersonId(String.valueOf(zhmkPerson.getId()));
                // 设置常驻人员
                tPerson.setType(0);
                // 设置允许通行
                tPerson.setAuthority(1);
                tPerson.setGender(1);
                tPerson.setState(0);
                FaceApiClick faceApiClick = FaceApiUtil.getFaceApiClick();
                int i = faceApiClick.addWhiteList(tPerson, zhmkDoorDevice.getIp());
                //添加人员进入map中
                Integer integer = personMap.get(zhmkPerson.getId());
                if(integer == null){
                    personMap.put(zhmkPerson.getId(),0);
                    integer = 0;
                }
                if(i !=0){
                    //失败
                    sendFailCount ++;
                    break;
                }
                sendSuccessCount ++;
                personMap.put(zhmkPerson.getId(),integer.intValue()+1);

            }
            SendPersonResponse sendPersonResponse = new SendPersonResponse();
            sendPersonResponse.setZhmkDoorDevice(zhmkDoorDevice);
            sendPersonResponse.setSendFailCount(sendFailCount);
            sendPersonResponse.setSendSuccessCount(sendSuccessCount);
            sendPersonResponseList.add(sendPersonResponse);

        }

        //人员状态修改，所有设备下发成功后，才算下发成功
        for (Map.Entry<Long, Integer> longIntegerEntry : personMap.entrySet()) {
            Integer value = longIntegerEntry.getValue();
            Long key = longIntegerEntry.getKey();
            ZhmkPerson zhmkPerson = new ZhmkPerson();
            zhmkPerson.setId(key);
            if(value == deviceIdList.size()){
                //所有设备下发成功
                zhmkPerson.setSendStatus(1);
            }else{
                //下发失败
                zhmkPerson.setSendStatus(0);
            }
            zhmkPersonMapper.updateZhmkPerson(zhmkPerson);
        }



        return AjaxResult.success(sendPersonResponseList);
    }

    /**
     * 人员删除
     * @param sendPersonRequest
     * @return
     */
    @Override
    public int personDelete(SendPersonRequest sendPersonRequest) {
        List<Long> deviceIdList = sendPersonRequest.getDeviceIdList();
        List<Long> personIdList = sendPersonRequest.getPersonIdList();
        if(personIdList.size()<=0){
            throw new CustomException("人员为空", HttpStatus.BAD_REQUEST);
        }
        Long[] ids = new Long[personIdList.size()];
        List<ZhmkPerson> zhmkPeopleList = zhmkPersonMapper.selectZhmkPersonListByIds(personIdList.toArray(ids));
        for (Long aLong : deviceIdList) {
            //根据设备id查询出设备信息
            ZhmkDoorDevice zhmkDoorDevice = zhmkDoorDeviceMapper.selectZhmkDoorDeviceById(aLong);
            if(zhmkDoorDevice == null){
                throw new CustomException("查询不到设备", HttpStatus.ERROR);
            }

            for (ZhmkPerson zhmkPerson : zhmkPeopleList) {
                FaceApiClick faceApiClick = FaceApiUtil.getFaceApiClick();
                int i = faceApiClick.deleteWhiteListPerson(zhmkDoorDevice.getIp(), String.valueOf(zhmkPerson.getId()));
            }

        }
        return 1;
    }

}
